#include "bluetoothmanager.h"

BluetoothManager::BluetoothManager() : socket(0), connected(false), server(false), lostLifeActivated(false), enemyLostLifeActivated(false) {
}

BluetoothManager::~BluetoothManager() {
}

void BluetoothManager::createServer() {
    server = true;
    qDebug() << "[BluetoothManager] Starting server!";
    bluetoothServer.startServer();
    connect(&bluetoothServer, SIGNAL(socketConnected(QBluetoothSocket*)), this, SLOT(handleConnected(QBluetoothSocket*)));
    connect(&bluetoothServer, SIGNAL(socketDisconnected()), this, SLOT(handleDisconnected()));
    connect(&bluetoothServer, SIGNAL(messageReceived(QString)), this, SLOT(handleMessage(QString)));

    emit serverModeSet();
}

void BluetoothManager::stopServer() {

    qDebug() << "[BluetoothManager] Stopping server!";
    bluetoothServer.stopServer();
}

void BluetoothManager::createClient() {
    server = false;
    qDebug() << "[BluetoothManager] Creating client!";
    bluetoothClient.discoverService();
    connect(&bluetoothClient, SIGNAL(socketConnected(QBluetoothSocket*)), this, SLOT(handleConnected(QBluetoothSocket*)));
    connect(&bluetoothClient, SIGNAL(socketDisconnected()), this, SLOT(handleDisconnected()));
    connect(&bluetoothClient, SIGNAL(noServiceFound()), this, SIGNAL(noServiceFound()));
    connect(&bluetoothClient, SIGNAL(messageReceived(QString)), this, SLOT(handleMessage(QString)));
}

void BluetoothManager::stopClient() {
    qDebug() << "[BluetoothManager] Stopping client!";
    bluetoothClient.stopClient();
}

void BluetoothManager::updatePosition(int x, int y) {
    NetworkMessage networkMessage("updateposition");
    networkMessage.setData("x", QString::number(x));
    networkMessage.setData("y", QString::number(y));

    sendMessage(networkMessage.serialize());
}

void BluetoothManager::throwBall(int x, int y, int speedX, int speedY) {
    NetworkMessage networkMessage("throwball");
    networkMessage.setData("x", QString::number(x));
    networkMessage.setData("y", QString::number(y));
    networkMessage.setData("speedX", QString::number(speedX));
    networkMessage.setData("speedY", QString::number(speedY));

    sendMessage(networkMessage.serialize());
}

void BluetoothManager::sendMessage(const QString &message) {
    if(connected) {
        QByteArray text = message.toUtf8() + '\n';
        socket->write(text);
    }
}

void BluetoothManager::handleMessage(QString message) {
    NetworkMessageParser parser;

    NetworkMessage msg = parser.parse(message);
    if(msg.getType() == "updateposition") {
        emit updatePositionEvent(msg.getData("x").toInt(), msg.getData("y").toInt());
    } else if(msg.getType() == "throwball") {
        emit throwBallEvent(msg.getData("x").toInt(), msg.getData("y").toInt(), msg.getData("speedX").toInt(), msg.getData("speedY").toInt());    
    } else if(msg.getType() == "lostlife") {
        emit lostLifeEvent();
    } else if(msg.getType() == "enemylostlife") {
        emit enemyLostLifeEvent();
    } else if(msg.getType() == "updatescore") {
        emit updateScoreEvent(msg.getData("myscore").toInt(), msg.getData("enemyscore").toInt());
    } else {
        qDebug() << "[BluetoothServer] Unknown message... skipping..." << msg.getType();
    }
}

void BluetoothManager::handleConnected(QBluetoothSocket *socket) {
    qDebug() << "[BluetoothManager] Connected!";
    qDebug() << "[BluetoothManager] Got socket!";
    this->socket = socket;

    connected = true;

    //lifeTimer.start(1000);
    //connect(&lifeTimer, SIGNAL(timeout()), this, SLOT(handleLifeTimer()));

    emit clientConnected();
}

void BluetoothManager::handleLifeTimer() {
    // lostLife
    if(lostLifeActivated) {
        qDebug() << "[BluetoothManager] Sending lostlife";
        NetworkMessage networkMessage("lostlife");
        sendMessage(networkMessage.serialize());

        lostLifeActivated = false;
    }

    // enemyLostLife
    if(enemyLostLifeActivated) {
        qDebug() << "[BluetoothManager] Sending enemylostlife";
        NetworkMessage networkMessage("enemylostlife");
        sendMessage(networkMessage.serialize());

        enemyLostLifeActivated = false;
    }
}

void BluetoothManager::handleDisconnected() {
    qDebug() << "[BluetoothManager] Disconnected!";
    //lifeTimer.stop();
    connected = false;
    emit clientDisonnected();
}

void BluetoothManager::lostLife() {
    if(!isServer()) return;
    qDebug() << "[BluetoothManager] lostLife flag activated!";
    lostLifeActivated = true;
}

void BluetoothManager::enemyLostLife() {
    if(!isServer()) return;
    qDebug() << "[BluetoothManager] enemyLostLife flag activated!";
    enemyLostLifeActivated = true;
}

bool BluetoothManager::isServer() {
    return server;
}

void BluetoothManager::updateScores(int my, int enemy) {
    if(!isServer()) return;

    NetworkMessage networkMessage("updatescore");
    networkMessage.setData("myscore", QString::number(my));
    networkMessage.setData("enemyscore", QString::number(enemy));

    sendMessage(networkMessage.serialize());
}
